<template>
  <el-card style="height: 80px;">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名：">
        <el-input v-model="keyword" placeholder="请输入搜索用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" :disabled="keyword?false:true">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0;">
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-button type="danger" :disabled="selectIdArr.length?false:true" @click="deleteSelectUser">批量删除</el-button>
    <el-table style="margin: 10px 0;" border :data="userArr" @selection-change="selectionChange">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column label="用户名字" align="center" prop="username"></el-table-column>
      <el-table-column label="用户名称" align="center" prop="name"></el-table-column>
      <el-table-column label="用户角色" align="center" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{row}">
          <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
          <el-button type="success" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
          <el-popconfirm :title="`确认删除${row.username}吗？`" width="260px" @confirm="deleteUser(row.id)">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <!-- 添加用户、修改用户 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{userParams.id?'更新用户':'添加用户'}}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input v-model="userParams.username" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="userParams.name" placeholder="请输入用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input v-model="userParams.password" placeholder="请输入用户密码"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 分配角色 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配用户角色</h4>
    </template>
    <template #default>
      <el-form ref="formRef">
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="userParams.name" :disabled="true" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(role,index) in allRole" :key="index" :label="role">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import {ref,onMounted,reactive,nextTick} from 'vue'
import {reqUserInfo,reqAddOrUpdateUser,reqAllRole,reqSetUserRole,reqRemoveUser,reqRemoveAllUser} from '@/api/acl/user/index'
import type {UserResponseData,Records,User,ALLRoleResponseData,ALLRole,SetRoleData} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus';
import useLayOutSettingStore from '@/store/modules/setting'
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let userArr = ref<Records>([])
let drawer = ref<boolean>(false)
let drawer1 = ref<boolean>(false)
let userParams = reactive<User>({
  username:'',
  name:'',
  password:'',
})
let formRef = ref<any>() //获取form组件实例
let checkAll = ref<boolean>(false) //全选状态
let isIndeterminate = ref<boolean>(false) //半选状态
let allRole = ref<ALLRole>([])
let userRole = ref<ALLRole>([])
let selectIdArr = ref<User[]>([]) //存储表格勾选项 批量删除的用户id
let keyword = ref<string>('')
// 获取模板setting仓库
let settingStore = useLayOutSettingStore()
onMounted(() => {
  getHasUser()
})
// 搜索按钮
const search = ()=>{
  getHasUser()
  keyword.value = ''
}
// 重置按钮
const reset = ()=>{
  settingStore.refsh = !settingStore.refsh
}
// 获取全部用户信息
const getHasUser = async(pager=1)=> {
  pageNo.value = pager
  let res:UserResponseData = await reqUserInfo(pageNo.value,pageSize.value,keyword.value)
  if(res.code==200){
    userArr.value = res.data.records
    total.value = res.data.total
  }
}
// 分页器下拉事件
const handler = ()=> {
  getHasUser()
}
const addUser = ()=> {
  drawer.value = true
  // 清空数据
  Object.assign(userParams,{
    id:0,
    username:'',
    name:'',
    password:'',
  })
  // 页面初次挂载时，没有form表单，
  // 第一次点击新增获取formRef.value时为undefined，拿不到组件实例，第二次可以拿到，
  // 为了解决第一次获取不到组件，使用nextTick，
  // 点击按钮后响应式数据发生变化，使用nextTick获取更新后的dom，再执行操作
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
const updateUser = (row:User)=> {
  drawer.value = true
  Object.assign(userParams,row)
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}
// 新增用户确认按钮
const save = async()=>{
  // 校验表单必填项，await等待所有表单项校验成功后再执行
  await formRef.value.validate()
  let res:any = await reqAddOrUpdateUser(userParams)
  if(res.code==200){
    drawer.value = false
    ElMessage.success(userParams.id?'更新成功！':'添加成功！')
    // getHasUser(userParams.id?pageNo.value:1)
    // 修改当前登录账号时，浏览器自动刷新一次，触发请求拦截器，回到登录页
    window.location.reload() //重载，刷新页面
  }else{
    drawer.value = false
    ElMessage.error(userParams.id?'更新失败！':'添加失败！')
  }
}
const cancel = ()=>{
  drawer.value = false
}
const validatorUsername = (rule:any,value:any,callBack:any)=>{
  // 用户名至少5位
  if(value.trim().length>=5){
    callBack()
  }else{
    callBack(new Error('用户名至少5位'))
  }
}
const validatorName = (rule:any,value:any,callBack:any)=>{
  // 用户名至少5位
  if(value.trim().length>=5){
    callBack()
  }else{
    callBack(new Error('用户昵称至少5位'))
  }
}
const validatorPassword = (rule:any,value:any,callBack:any)=>{
  // 用户名至少5位
  if(value.trim().length>=6){
    callBack()
  }else{
    callBack(new Error('用户密码至少6位'))
  }
}
// 表单校验规则对象
const rules = {
  username:[{ required: true, trigger: 'blur',validator:validatorUsername }],
  name:[{ required: true, trigger: 'blur',validator:validatorName }],
  password:[{ required: true, trigger: 'blur',validator:validatorPassword }],
}
// 分配角色 显示抽屉
const setRole = async(row:User)=> {
  Object.assign(userParams,row) //回显用户名字name
  // 获取全部职位数据，当前用户已有职位数据
  let res:ALLRoleResponseData = await reqAllRole((userParams.id as number)) //as断言：务必是number的时候进行传参
  if(res.code==200){
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
    drawer1.value = true
  }
}
// 全选复选框触发事件
const handleCheckAllChange = (val: boolean) => {
  // val:true 全选 false 全不选
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 复选框勾选事件
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}
// 分配职务确认按钮
const confirmClick = async()=> {
  let data:SetRoleData = {
    userId:(userParams.id as number),
    roleIdList:userRole.value.map(item => {
      return (item.id as number)
    })
  }
 let res = await reqSetUserRole(data)
 if(res.code==200){
  ElMessage.success('分配成功！')
  drawer1.value = false
  getHasUser(pageNo.value)
 }else{
  ElMessage.error('分配失败！')
 }
}
// 删除单行用户
const deleteUser = async(userId:number)=>{
  let res:any = await reqRemoveUser(userId)
  if(res.code==200){
    ElMessage.success('删除成功！')
    getHasUser(userArr.value.length>1?pageNo.value:pageNo.value-1)
  }else{
    ElMessage.error('删除失败！')
  }
}
// table复选框勾选时 触发事件
const selectionChange = (value:any)=> {
  selectIdArr.value = value
}
// 批量删除
const deleteSelectUser = async()=> {
  let idsList:any = selectIdArr.value.map(item => {
    return item.id
  })
 let res:any = await reqRemoveAllUser(idsList)
 if(res.code==200){
    ElMessage.success('批量删除成功！')
    getHasUser(userArr.value.length>1?pageNo.value:pageNo.value-1)
  }else{
    ElMessage.error('批量删除失败！')
  }
} 
</script>

<style scoped lang="scss">
.form{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>